package deployr.core;

import static java.text.MessageFormat.*;

import java.util.regex.*;

public class Artifact {

	private final Pattern pattern = Pattern.compile("^(.*):(.*):(.*)$");

	private final String fingerprint;

	private final String path;

	public Artifact(final String fingerprint) {
		this.fingerprint = fingerprint;
		this.path = fingerprint;
	}

	public Artifact(final String groupId, final String artifactId, final String version) {
		fingerprint = format("{0}:{1}:{2}", groupId, artifactId, version);
		path = format("/{0}/{1}/{2}", groupId().replaceAll("\\.", "/"), artifactId(), version());
	}

	public Artifact(final String groupId, final String artifactId, final String version, final String update) {
		fingerprint = format("{0}:{1}:{2}:{3}", groupId, artifactId, version, update);
		path = format("/{0}/{1}/{2}/{3}", groupId.replaceAll("\\.", "/"), artifactId, version, update);
	}

	public String artifactId() {
		return token(2);
	}

	@Override
	public boolean equals(final Object obj) {
		if (!Artifact.class.isAssignableFrom(obj.getClass())) return false;
		return ((Artifact) obj).fingerprint.equals(fingerprint);
	}

	public String groupId() {
		return token(1);
	}

	public String checksum() {
		return Checksums.md5(fingerprint);
	}

	private String token(final int group) {
		final Matcher m = pattern.matcher(fingerprint);
		if (!m.matches()) return "unknown";
		return m.group(group);
	}

	@Override
	public String toString() {
		return fingerprint;
	}

	public String version() {
		return token(3);
	}

	public String path() {
		return path;
	}

}
